<!-- 用户编辑弹窗 -->
<template>
  <el-dialog
    width="680px"
    :visible="visible"
    :lock-scroll="false"
    :destroy-on-close="true"
    custom-class="ele-dialog-form"
    :title="isUpdate?'修改学校':'添加学校'"
    @update:visible="updateVisible">
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      label-width="82px">
      <el-row :gutter="15">
        <el-col :sm="12">
          <el-form-item label="学校名称:" prop="title">
            <el-input
              clearable
              :maxlength="20"
              v-model="form.title"
              placeholder="请输入学校名称"/>
          </el-form-item>
          </el-col>
          <el-col :sm="12">
            <el-form-item label="排序号:" prop="sort">
              <el-input-number
                :min="0"
                v-model="form.sort"
                placeholder="请输入排序号"
                controls-position="right"
                class="ele-fluid ele-text-left"/>
            </el-form-item>
          </el-col>
          <el-col :sm="12">
          <el-form-item label="所在城市:" prop="district_code">
            <el-cascader
              clearable
              v-model="city"
              class="ele-fluid"
              placeholder="请选择省市区"
              :options="regions.cityData"
              ref="district_code"
              @change="handleCityChange"
              popper-class="ele-pop-wrap-higher"/>
          </el-form-item>
          </el-col>
          <el-col :sm="12">
            <el-form-item label="街道:" prop="streets_code">
              <el-select style="width:100%" clearable
              :disabled="!form.district_code"
              v-model="form.streets_code"
              @change="changeInp"
              placeholder="请输入街道">
                <el-option :value="item.streets_code" :label="item.ext_name" v-for="(item,index) in streetsList" :key="index"/>
              </el-select>
          </el-form-item>
          </el-col>
      </el-row>
      <el-form-item label="详细地址:" prop="address">
        <el-input
          clearable
          :maxlength="150"
          v-model="form.address"
          placeholder="请输入详细地址"/>
      </el-form-item>
    </el-form>
    <div slot="footer">
      <el-button
        @click="updateVisible(false)">取消
      </el-button>
      <el-button
        type="primary"
        :loading="loading"
        @click="save">保存
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
// import Treeselect from '@riophae/vue-treeselect' // 下拉树
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import regions from 'ele-admin/packages/regions';

export default {
  name: 'UserEdit',
  props: {
    // 弹窗是否打开
    visible: Boolean,
    // 修改回显的数据
    data: Object,
  },
  // components: { Treeselect},
  data() {
    return {
      // 省市区数据
      regions: regions,
      // 选中的省市区
      city: [],
      streetsList:[],
      // 选中的省市
      provinceCity: [],
      // 选中的省
      province: [],
      // 表单数据
      form: Object.assign({status: 1}, this.data),
      // 表单验证规则
      rules: {
        // username: [
        //   {
        //     required: true,
        //     type: 'string',
        //     trigger: 'blur',
        //     validator: (rule, value, callback) => {
        //       if (!value) {
        //         return callback(new Error('请输入用户账号'));
        //       }
        //       this.$http.get('/user/checkUser?username=' + value).then(res => {
        //         if (res.data.code !== 0 || !res.data.data.length) {
        //           return callback();
        //         }
        //         if (this.isUpdate && res.data.data[0].username === this.data.username) {
        //           return callback();
        //         }
        //         callback(new Error('账号已经存在'));
        //       }).catch(() => {
        //         callback();
        //       });
        //     }
        //   }
        // ],
        title: [
          {required: true, message: '请输入学校名称', trigger: 'blur'}
        ],
        district_code: [
          {required: true, message: '请选择省市区', trigger: 'blur'}
        ],
        streets_code: [
          {required: true, message: '请选择街道', trigger: 'blur'}
        ],
        sort: [
          {required: true, message: '请输入排序号', trigger: 'blur'}
        ],
        // address: [
        //   {required: true, message: '请输入详细地址', trigger: 'blur'}
        // ]
      },
      // 提交状态
      loading: false,
      // 是否是修改
      isUpdate: false,
      // 角色列表
      roleList: [],
      // 职级列表
      levelList: [],
      // 岗位列表
      positionList: [],
      // 部门列表
      deptList: [],
    };
  },
  watch: {
    data(vel) {
      if (vel) {
        let obj=JSON.parse(JSON.stringify(vel))
        // this.form = Object.assign({}, this.data, {
        //   // role_ids: this.data.roles.map(d => d.id)
        // });
        // 取值赋予城市组件
        if(obj.id){
          this.isUpdate=true
        }
        this.form = {
          id:obj.id,
          title:obj.title || '',
          province_code:obj.province_code || '',
          city_code:obj.city_code || '',
          district_code:obj.district_code || '',
          streets_code:obj.streets_code || '',
          address:obj.address || '',
          sort:obj.sort || '',
        };
        this.city = [obj.province_code,obj.city_code,obj.district_code];
        // 清空密码输入框
      } else {
        this.form = {};
        this.isUpdate = false
        // 清空省市区控件
        this.city = [];
      }
    },
    city(val,old) {
      console.log("city",val,old)
      if (val && val.length > 0) { 
        this.form.province_code=val[0]
        this.form.city_code=val[1]
        this.form.district_code = val[2]
        if (this.form.district_code) {
          this.getStreetsList()
        }
      }
    },
    // 'form.streets_code'(val){
    //   if(val){
    //     this.city[3]=val
    //   }else{
        
    //   }
    // }
  },
  mounted() {
  },
  methods: {
    handleCityChange() {
      this.isUpdate=false
    },
    changeInp(){
      this.$forceUpdate()
    },
    getStreetsList() {
      this.$http
        .get("/user/getStreetsList", { params: { district_code: this.form.district_code } })
        .then(res => {
          this.$nextTick(()=>{
            this.streetsList = res.data.data;
            if(this.isUpdate){
              this.form.streets_code=this.data.streets_code
            } else {
              this.form.streets_code=''
            }
          })
        })
        .catch(e => {
          this.$message.error(e.message);
        });
    },
    /* 保存编辑 */
    save() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          let nodes=this.$refs.district_code.getCheckedNodes(false)
          this.loading = true;
          // 城市数据处理
          this.form = Object.assign({}, this.form, {
            city: this.city
          });
          let params = {
            ...this.form,city:[...this.form.city,this.form.streets_code],
            location:`${nodes[0].parent.parent.label}${nodes[0].parent.label}${nodes[0].label}${this.streetsList.find(item=>item.streets_code===this.form.streets_code).ext_name}`
           }
          this.$http.post('/schoole/edit', params).then(res => {
            this.loading = false;
            if (res.data.code === 0) {
              this.$message({type: 'success', message: res.data.msg});
              if (!this.isUpdate) {
                this.form = {};
              }
              this.updateVisible(false);
              this.$emit('done');
            } else {
              this.$message.error(res.data.msg);
            }
          }).catch(e => {
            this.loading = false;
            this.$message.error(e.message);
          });
        } else {
          return false;
        }
      });
    },
    /* 更新visible */
    updateVisible(value) {
      this.$emit('update:visible', value);
    }
  }
}
</script>

<style scoped>
</style>
